<template>
  <el-dialog
    v-model="dialogVisible"
    title="📈 销售分析看板"
    width="90%"
    top="5vh"
    class="analytics-dialog"
    @opened="fetchData"
  >
    <!-- 时间筛选 -->
    <div class="filter-bar">
      <el-radio-group v-model="timeRange" @change="fetchData">
        <el-radio-button label="week">最近一周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="quarter">本季度</el-radio-button>
      </el-radio-group>
    </div>

    <!-- 数据看板 -->
    <div v-loading="loading" class="dashboard-container">
      <!-- 指标卡片 -->
      <div class="metric-cards">
        <div class="metric-card">
          <div class="mc-icon" style="background: #409EFF">
            <el-icon><Money /></el-icon>
          </div>
          <div class="mc-content">
            <div class="value">¥ {{ formatNumber(stats.totalSales) }}</div>
            <div class="title">总销售额</div>
          </div>
        </div>

        <div class="metric-card">
          <div class="mc-icon" style="background: #67C23A">
            <el-icon><Tickets /></el-icon>
          </div>
          <div class="mc-content">
            <div class="value">{{ formatNumber(stats.totalOrders) }}</div>
            <div class="title">总订单量</div>
          </div>
        </div>
      </div>

      <!-- 核心图表 -->
      <div class="chart-row">
        <div class="chart-container">
          <h3>📈 销售趋势</h3>
          <v-chart :key="'trend'+chartKey" :option="trendChart" autoresize />
        </div>
        <div class="chart-container">
          <h3>📦 订单状态分布</h3>
          <v-chart :key="'status'+chartKey" :option="statusChart" autoresize />
        </div>
      </div>

      <div class="chart-row">
        <div class="chart-container">
          <h3>🏆 热销商品 TOP10</h3>
          <v-chart :key="'product'+chartKey" :option="productChart" autoresize />
        </div>
      </div>
    </div>

    <!-- 操作栏 -->
    <template #footer>
      <el-button @click="exportData">导出报表</el-button>
      <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watchEffect, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import axios from 'axios'
import { Money, Tickets } from '@element-plus/icons-vue'
import { debounce } from 'lodash-es'
import html2canvas from 'html2canvas'
import { jsPDF } from "jspdf"
import autoTable from 'jspdf-autotable'
import { ElMessage } from 'element-plus'
// 注册ECharts组件
echarts.use([
  CanvasRenderer,
  LineChart,
  BarChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
])

// 状态颜色映射（确保与后端返回的statusDistribution键名完全一致）
const statusColors = {
  '待付款': '#F56C6C',
  '已付款': '#67C23A',
  '已发货': '#409EFF',
  '已完成': '#E6A23C'
}

export default {
  components: { VChart },
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    sellerId: {
      type: Number,
      required: true
    }
  },
  emits: ['update:visible'],
  setup(props, { emit }) {
    // 响应式状态
    const loading = ref(false)
    const timeRange = ref('month')
    const chartKey = ref(0)
    const stats = reactive({
      totalSales: 0,
      totalOrders: 0,
      statusDistribution: {},
      popularProducts: {},
      timeSeries: {}
    })

    // 防抖的resize处理
    const handleResize = debounce(() => {
      try {
        const instances = [
          ...document.querySelectorAll('.chart-container')
        ].map(dom => echarts.getInstanceByDom(dom))
        
        instances.forEach(instance => {
          if (instance && !instance.isDisposed()) {
            instance.resize()
          }
        })
      } catch (e) {
        console.warn('Resize error:', e)
      }
    }, 500)

    // 窗口resize监听
    window.addEventListener('resize', handleResize)
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize)
    })

    // 控制对话框显示
    const dialogVisible = computed({
      get: () => props.visible,
      set: (val) => emit('update:visible', val)
    })

    // 趋势图表配置
    const trendChart = reactive({
      tooltip: {
        trigger: 'axis',
        formatter: (params) => {
          const date = params[0].axisValue
          const value = params[0].value
          return `${date}<br/>销售额：¥${Number(value).toLocaleString()}`
        }
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          rotate: 45,
          formatter: (value) => {
            if (/\d+-\d+/.test(value)) {
              const [month, year] = value.split('-')
              return `${year}年${month}月`
            }
            return value
          }
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => `¥${Number(value).toLocaleString()}`
        }
      },
      series: [{
        name: '销售额',
        type: 'line',
        smooth: true,
        areaStyle: {
          color: 'rgba(64, 158, 255, 0.2)'
        },
        itemStyle: {
          color: '#409EFF'
        },
        data: []
      }],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      }
    })

    // 状态分布图表（修复数据绑定问题）
    const statusChart = reactive({
      tooltip: {
        trigger: 'item',
        formatter: ({ name, value, percent }) => 
          `${name}<br/>数量：${value}（${percent}%）`
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: []
      },
      series: [{
        type: 'pie',
        radius: '60%',
        data: [],
        itemStyle: {
          color: (params) => statusColors[params.name] || '#909399'
        },
        label: {
          show: true,
          formatter: '{b}: {c} ({d}%)'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }]
    })

    // 商品销售图表（修复数据格式问题）
    const productChart = reactive({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        },
        formatter: (params) => {
          const data = params[0]
          return `商品ID：${data.name}<br/>销量：${data.value}件`
        }
      },
      xAxis: {
        type: 'category',
        data: [],
        axisLabel: {
          rotate: 45,
          formatter: (value) => `#${value}`
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: value => `${value}件`
        }
      },
      series: [{
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#67C23A'
        },
        barMaxWidth: 40,
        label: {
          show: true,
          position: 'top'
        }
      }],
      grid: {
        left: '3%',
        right: '4%',
        bottom: '15%',
        containLabel: true
      }
    })

    // 数据获取方法（修复响应式更新问题）
    const fetchData = async () => {
      try {
        loading.value = true
        const { data } = await axios.get('http://localhost:8092/order/analyzeSales', {
          params: {
            sellerId: props.sellerId,
            range: timeRange.value
          }
        })

        if (data.code === 200) {
          // 使用深拷贝确保响应式更新
          const rawData = JSON.parse(JSON.stringify(data.data))
          Object.keys(rawData).forEach(key => {
            stats[key] = rawData[key]
          })

          await nextTick()

          // 处理时间序列（修复排序问题）
          const timeEntries = Object.entries(stats.timeSeries)
            .map(([date, value]) => ({
              date,
              value: Number(value),
              sortKey: date.includes('-') 
                ? date.split('-').reverse().join('-') 
                : date
            }))
            .sort((a, b) => a.sortKey.localeCompare(b.sortKey))
          
          trendChart.xAxis.data = timeEntries.map(item => item.date)
          trendChart.series[0].data = timeEntries.map(item => item.value)

          // 处理状态分布（确保数据正确性）
          const statusData = Object.entries(stats.statusDistribution)
            .filter(([_, value]) => Number(value) > 0)
            .map(([name, value]) => ({
              name,
              value: Number(value),
              itemStyle: { color: statusColors[name] }
            }))
          
          statusChart.series[0].data = [...statusData]
          statusChart.legend.data = [...statusData.map(d => d.name)]

          // 处理热销商品（修复排序和格式问题）
          const products = Object.entries(stats.popularProducts)
            .map(([id, count]) => ({
              id: String(id),
              count: Number(count)
            }))
            .sort((a, b) => b.count - a.count)
            .slice(0, 10)
          
          productChart.xAxis.data = [...products.map(p => p.id)]
          productChart.series[0].data = [...products.map(p => p.count)]

          // 强制图表更新
          chartKey.value++
          setTimeout(handleResize, 300)
        }
      } catch (error) {
        console.error('数据获取失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 导出数据（保持不变）
    const exportData = async () => {
  try {
    loading.value = true
    const doc = new jsPDF('landscape', 'mm', 'a4')
    
    // 添加标题
    doc.setFontSize(18)
    doc.text('销售分析报告', 105, 20, { align: 'center' })
    
    // 添加基础数据表格
    autoTable(doc, {
      startY: 30,
      head: [['指标', '数值']],
      body: [
        ['时间范围', timeRange.value],
        ['总销售额', `¥${stats.totalSales.toLocaleString()}`],
        ['总订单量', stats.totalOrders.toLocaleString()]
      ],
      theme: 'grid',
      styles: { fontSize: 12 },
      headStyles: { fillColor: [64, 158, 255] }
    })

    // 图表截图方法
    const captureChart = async (selector) => {
      const canvas = await html2canvas(document.querySelector(selector), {
        useCORS: true,
        scale: 2
      })
      return canvas.toDataURL('image/png')
    }

    // 截取所有图表
    const charts = await Promise.all([
      captureChart('.chart-container:nth-child(1)'),
      captureChart('.chart-container:nth-child(2)'),
      captureChart('.chart-container:nth-child(3)')
    ])

    // 添加图表到PDF
    let yPosition = doc.lastAutoTable.finalY + 10
    charts.forEach((imgData) => {
      const pageWidth = doc.internal.pageSize.getWidth()
      const imgWidth = pageWidth - 20
      const imgHeight = (imgWidth * 0.75) // 保持4:3宽高比
      
      if (yPosition + imgHeight > 280) {
        doc.addPage()
        yPosition = 10
      }
      
      doc.addImage(imgData, 'PNG', 10, yPosition, imgWidth, imgHeight)
      yPosition += imgHeight + 10
    })

    // 添加时间序列数据
    autoTable(doc, {
      startY: yPosition,
      head: [['时间段', '销售额']],
      body: Object.entries(stats.timeSeries).map(([date, amount]) => [
        date, 
        `¥${Number(amount).toLocaleString()}`
      ]),
      styles: { fontSize: 10 },
      columnStyles: {
        0: { cellWidth: 60 },
        1: { cellWidth: 40 }
      }
    })

    doc.save(`销售分析_${new Date().toISOString().slice(0,10)}.pdf`)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

    // 监听sellerId变化重新获取数据
    watchEffect(() => {
      if (props.sellerId && dialogVisible.value) {
        fetchData()
      }
    })

    return {
      dialogVisible,
      loading,
      timeRange,
      stats,
      trendChart,
      statusChart,
      productChart,
      chartKey,
      formatNumber: (num) => Number(num || 0).toLocaleString(),
      fetchData,
      exportData
    }
  }
}
</script>

<style scoped>
.analytics-dialog {
  .el-dialog__body {
    padding: 15px 20px;
    position: relative;
    z-index: 1;
  }
  
  .dashboard-container {
    height: 70vh;
    overflow-y: auto;
  }

  .metric-cards {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    margin-bottom: 24px;
  }

  .metric-card {
    display: flex;
    align-items: center;
    padding: 16px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);

    .mc-icon {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 16px;
      
      .el-icon {
        font-size: 24px;
        color: white;
      }
    }

    .mc-content {
      .value {
        font-size: 24px;
        font-weight: 600;
        color: #2c3e50;
      }
      
      .title {
        color: #7f8c8d;
        font-size: 14px;
      }
    }
  }

  .chart-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
    margin-bottom: 24px;

    &:last-child {
      grid-template-columns: 1fr;
    }
  }

  .chart-container {
    position: relative;
    background: white !important;
    box-shadow: none !important;
    border-radius: 8px;
    padding: 16px;
    /* box-shadow: 0 2px 8px rgba(0,0,0,0.1); */
    height: 400px;
    width: 100%;
    overflow: hidden;
    z-index: 0;
    
    h3 {
      margin: 0 0 16px;
      color: #2c3e50;
      font-size: 16px;
    }
  }
}

/* 修复图表尺寸问题 */  
.echarts {
  width: 100% !important; 
  height: calc(100% - 40px) !important; /* 留出标题空间 */
  min-height: unset !important;
}
</style>